package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    @Autowired
    @Lazy
    private StudentService studentService;

    @Override
    public PageResult paginatedQueries(EmpQueryParam param) {
        Page<Clazz> clazzPage = Page.of(param.getPage(), param.getPageSize());
        Page<Clazz> page = lambdaQuery().like(StrUtil.isNotBlank(param.getName()), Clazz::getName, param.getName())
                .between(ObjectUtil.isNotNull(param.getBegin()) && ObjectUtil.isNotNull(param.getEnd()), Clazz::getBeginDate, param.getBegin(), param.getEnd())
                .page(clazzPage);
        List<Clazz> records = page.getRecords();
        //获取当前时间
        LocalDate now = LocalDate.now();
        records.forEach(clazz -> {
            //判断班级是否开课
            if (clazz.getEndDate().isBefore(now)) {
                clazz.setStatus("已结束");
            } else if (clazz.getBeginDate().isAfter(now)) {
                clazz.setStatus("未开始");
            } else {
                clazz.setStatus("进行中");
            }
            //调用员工Service层，根据班级表中的员工id查询员工信息的所有信息
            Emp emp = empService.getById(clazz.getMasterId());
            //如果查询到的员工不为空，则给班级的负责人赋值成员工的姓名
            if (emp != null) {
                clazz.setMasterName(emp.getName());
            }
        });
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void clazzremoveById(Integer id) {
        long count = studentService.count(new LambdaQueryWrapper<Student>().eq(Student::getClazzId, id));
        if (count > 0) {
            throw new RuntimeException();
        }
        removeById(id);

    }
}
